package leetcode.code0840;

import leetcode.IDebug;

public class Solution implements IDebug {

	int[][] grid;

	public int numMagicSquaresInside(int[][] grid) {
		this.grid = grid;
		int m = grid.length, n = grid[0].length;
		int ans = 0;
		for (int i = 1; i < m - 1; i++) {
			for (int j = 1; j < n - 1; j++) {
				if (grid[i][j] == 5)// 看官解，后知后觉，人工智能，塞高
					ans += this.isMagicSquares(i, j);
			}
		}
		return ans;
	}

	private int isMagicSquares(int x, int y) {
		int hash = 0;
		int[] col = new int[3];
		int l = 0, r = 0;
		for (int i = x - 1, p1 = y - 1, p2 = y + 1; i < x + 2; i++, p1++, p2--) {
			int row = 0;
			for (int j = y - 1, p = 0; j < y + 2; j++, p++) {
				int num = this.grid[i][j];
				if ((hash >> num & 1) == 1 || num > 9 || num < 1) {
					return 0;
				}
				hash |= 1 << num;
				row += num;
				col[p] += num;
			}
			if (row != 15) {
				return 0;
			}
			l += this.grid[i][p1];
			r += this.grid[i][p2];
		}
		if (col[0] != 15 || col[1] != 15 || col[2] != 15 || l != r || l != 15) {
			return 0;
		}
		return 1;
	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
